package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
)

// VideoResponse 定义从 API 返回的数据结构
type VideoResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		Video string `json:"video"`
	} `json:"data"`
}

func main() {
	// 第一步：发送请求获取视频链接
	apiURL := "https://api.52vmy.cn/api/video/girl"
	resp, err := http.Get(apiURL)
	if err != nil {
		fmt.Println("Error fetching video URL:", err)
		return
	}
	defer resp.Body.Close()

	// 第二步：读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	// 第三步：解析 JSON 响应
	var videoResponse VideoResponse
	err = json.Unmarshal(body, &videoResponse)
	if err != nil {
		fmt.Println("Error unmarshaling response data:", err)
		return
	}

	// 检查 API 返回的状态码
	if videoResponse.Code != 200 {
		fmt.Println("Failed to fetch video URL:", videoResponse.Msg)
		return
	}

	// 提取视频链接
	videoURL := videoResponse.Data.Video
	fmt.Println("视频链接：", videoURL)

	// 第四步：下载视频到本地
	if videoURL == "" {
		fmt.Println("视频链接为空，无法下载。")
		return
	}

	// 创建本地文件
	localVideoPath := filepath.Join(".", "video.mp4") // 下载到当前目录下
	file, err := os.Create(localVideoPath)
	if err != nil {
		fmt.Println("Error creating local file:", err)
		return
	}
	defer file.Close()

	// 下载视频
	resp, err = http.Get(videoURL)
	if err != nil {
		fmt.Println("Error downloading video:", err)
		return
	}
	defer resp.Body.Close()

	_, err = io.Copy(file, resp.Body)
	if err != nil {
		fmt.Println("Error saving video to local file:", err)
		return
	}
	fmt.Println("视频已下载到本地：", localVideoPath)

	// 第五步：使用系统默认播放器打开视频
	openCommand := ""
	switch runtime.GOOS {
	case "windows":
		openCommand = "start"
	case "darwin": // macOS
		openCommand = "open"
	default: // Linux
		openCommand = "xdg-open"
	}

	_ = openCommand
	// cmd := exec.Command(`C:\Program Files (x86)\Windows Media Player\wmplayer.exe`, localVideoPath)
	cmd := exec.Command("C:\\WinDev\\ffmpeg\\ffplay.exe", "-i", localVideoPath)
	// cmd := exec.Command(openCommand, localVideoPath)
	err = cmd.Start()
	if err != nil {
		fmt.Println("Error opening video in default player:", err)
		return
	}

	fmt.Println("视频正在播放...")
}
